import requests
import os
import logging

# GitLab服务器地址
GITLAB_URL = 'https://xxx'
# 组的名称
GROUP_NAMES = ['bankbj', 'bylc_projects']
# 访问令牌，用于身份验证
ACCESS_TOKEN = 'ccc'

PATH = 'D:/projectbak'

# 设置身份验证头
headers = {
    'Authorization': f'Bearer {ACCESS_TOKEN}'
}


def get_by_group(group, path):
    print()
    print('处理组 ' + group + ', 路径 ' + path)
    if not os.path.exists(path):
        print('创建目录: ' + path)
        os.mkdir(path)

    os.chdir(path)

    # 查项目
    url_getproject = f'{GITLAB_URL}/api/v4/groups/{group}/projects?per_page=100&include_subgroups=yes'
    print(url_getproject)
    response = requests.get(url_getproject, headers=headers)
    project_infos = response.json()
    for project_info in project_infos:
        print(project_info)
        project_url = project_info['http_url_to_repo']
        project_name = project_info['name']
        project_dir = f'./{project_name}'
        print(project_url)
        # 克隆项目
        # os.system(f'git clone --recursive {project_url} {project_dir}')

    # 查子组
    url_getsubgroup = f'{GITLAB_URL}/api/v4/groups/{group}/subgroups?per_page=100'
    response = requests.get(url_getsubgroup, headers=headers)
    project_infos = response.json()
    for project_info in project_infos:
        # print(project_info)
        web_url = project_info['web_url']
        project_name = project_info['name']
        subgroup = group + '/' + project_name
        subpath = path + '/' + project_name
        print(web_url)
        # get_by_group(subgroup, subpath)

    return

# 遍历组
for group_name in GROUP_NAMES:
    get_by_group(group_name, PATH + '/' + group_name)
